import axios from "axios";
//加解密
import { decryptECB, encryptECB } from "../crypt/index"
//持久化
import { session_cache_key, public_secret_key, token_cache_key } from '../cache/cacheKey'
import { setCache, getCache } from '../cache'

//私钥
const privateKey = 'QHilvk7D3Phq766hQHilvk7D3Phq766h';
//baseURL
const development = 'http://172.26.2.18:3001';



//axios
export const networkRequest = axios;

//session配置
export const sessionConfig = {
    baseURL: development,
    url: '***',
    data: '***',
    method: 'post',
    timeout: 1000 * 60,
    headers: {
        'Content-Type': 'text/plain;charset=UTF-8',
    },
    transformRequest: [function (data, headers) {
        // 对发送的 data 进行任意转换处理
        //1、对象转字符串
        const str = JSON.stringify(data);
        //2、私钥加密
        const newData = encryptECB(str, privateKey);
        return newData;
    }],
    transformResponse: [function (data) {
        // 对接收的 data 进行任意转换处理
        if (isJSON(data)) {
            //错误处理:非密文->转json对象
            const newData = JSON.parse(data);
            return newData;
        } else {
            //密文
            //1、私钥解密
            const str = decryptECB(data, privateKey);
            //2、字符串转对象
            const newData = JSON.parse(str);
            //保存sessionID和publicKey
            setCache(session_cache_key, newData.data.sessionId);
            setCache(public_secret_key, newData.data.publicKey);
            return newData;
        }
    }],
}

//基础配置
export const baseRequestConfig = {
    baseURL: development,
    url: '***',
    data: '***',
    method: 'post',
    timeout: 1000 * 60,
    headers: {
        'Content-Type': 'text/plain;charset=UTF-8',
    },
    transformRequest: [function (data, headers) {
        // 对发送的 data 进行任意转换处理
        //请求头增加session
        headers.sessionId = getCache(session_cache_key);
        //请求体增加token
        data.set('token', getCache(token_cache_key))
        //1、map转对象
        const str = Object.fromEntries(data);
        //2、对象转字符串
        const str1 = JSON.stringify(str);
        //2、私钥+公钥=真实密钥加密处理
        const realKey = getRealKey();
        //3、用真实密钥加密
        const newData = encryptECB(str1, realKey);
        return newData;
    }],
    transformResponse: [function (data) {
        // 对接收的 data 进行任意转换处理
        if (isJSON(data)) {
            //错误处理:非密文->转json对象
            const newData = JSON.parse(data);
            return newData;
        } else {
            //密文
            //1、私钥+公钥=真实密钥解密处理
            const realKey = getRealKey();
            const str = decryptECB(data, realKey);
            //2、字符串转对象
            const newData = JSON.parse(str);
            return newData;
        }
    }],
}

function isJSON(str) {
    try {
        JSON.parse(str);
        return true;
    } catch (e) {
        return false;
    }
}

function getRealKey() {
    let signature1 = privateKey.substring(0, 15);
    let signature2 = getCache(public_secret_key).substring(15, 32);
    return signature1 + signature2;
}